package com.jhgsys.internal.accident.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jhgsys.internal.accident.dto.AccidentSurveyTeamDto;
import com.jhgsys.internal.accident.entity.AccidentSurveyTeam;
import com.jhgsys.internal.accident.entity.AccidentSurveyTeamUser;
import com.jhgsys.internal.accident.mapper.AccidentSurveyTeamMapper;
import com.jhgsys.internal.accident.service.IAccidentSurveyTeamService;
import com.jhgsys.internal.accident.service.IAccidentSurveyTeamUserService;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  Service实现
 *
 * @author zhangwei
 * @date 2024-09-11 15:21:32
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AccidentSurveyTeamServiceImpl extends ServiceImpl<AccidentSurveyTeamMapper, AccidentSurveyTeam> implements IAccidentSurveyTeamService {

    @Autowired
    private IAccidentSurveyTeamUserService accidentSurveyTeamUserService;

    /**
     * 查询（分页）
     * @author zhangwei
     * @date 2024-09-11 15:21:32
     * @param request QueryRequest
     * @param accidentSurveyTeamDto accidentSurveyTeamDto
     * @return IPage<AccidentSurveyTeam>
    */
    @Override
    public IPage<AccidentSurveyTeamDto> findAccidentSurveyTeamPage(QueryRequest request, AccidentSurveyTeamDto accidentSurveyTeamDto) {
        AccidentSurveyTeam accidentSurveyTeam = BeanHelper.copyProperties(accidentSurveyTeamDto,AccidentSurveyTeam.class);
        IPage<AccidentSurveyTeamDto> result = new Page<>(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<AccidentSurveyTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccidentSurveyTeam::getDeletedFlg, 0);
        // TODO 设置查询条件
        queryWrapper.eq(AccidentSurveyTeam::getDeletedFlg, FebsConstant.VALID);
        if(StringUtils.isNotBlank(accidentSurveyTeam.getStatus())){
            queryWrapper.eq(AccidentSurveyTeam::getStatus,accidentSurveyTeam.getStatus() );
        }
        if(StringUtils.isNotBlank(accidentSurveyTeam.getTenantId())){
            queryWrapper.eq(AccidentSurveyTeam::getTenantId,accidentSurveyTeam.getTenantId() );
        }
        if(StringUtils.isNotBlank(accidentSurveyTeam.getDutyName())){
            queryWrapper.like(AccidentSurveyTeam::getDutyName,accidentSurveyTeam.getDutyName());
        }
        if(StringUtils.isNotBlank(accidentSurveyTeamDto.getRealName())){
            queryWrapper.apply(" survey_team_id in (SELECT survey_team_id FROM accident_survey_team_user WHERE real_name like '%"+accidentSurveyTeamDto.getRealName()+"%' AND deleted_flg = '0') ");
        }
        queryWrapper.orderByAsc(AccidentSurveyTeam::getSort);

        Page<AccidentSurveyTeam> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<AccidentSurveyTeam> pages = this.page(page, queryWrapper);
        List<AccidentSurveyTeam> accidentSurveyTeamList = pages.getRecords();
        List<AccidentSurveyTeamDto> list = new ArrayList<>();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(accidentSurveyTeamList)){
            list = BeanHelper.copyWithCollection(accidentSurveyTeamList,AccidentSurveyTeamDto.class);
        }
        list.forEach(d -> {
            List<AccidentSurveyTeamUser> teamUserList = accidentSurveyTeamUserService.list(new LambdaQueryWrapper<AccidentSurveyTeamUser>().eq(AccidentSurveyTeamUser::getSurveyTeamId,d.getSurveyTeamId()));
            d.setTeamUserList(teamUserList);
        });
        result.setRecords(list);
        result.setTotal(list.size());

        return result;
    }

    /**
     * 查询（所有）
     * @author zhangwei
     * @date 2024-09-11 15:21:32
     * @param accidentSurveyTeam accidentSurveyTeam
     * @return List<AccidentSurveyTeam>
     */
    @Override
    public List<AccidentSurveyTeam> findAccidentSurveyTeamList(AccidentSurveyTeam accidentSurveyTeam) {
	    LambdaQueryWrapper<AccidentSurveyTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccidentSurveyTeam::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author zhangwei
    * @date 2024-09-11 15:21:32
    * @param id
    * @return AccidentSurveyTeam
    */
    @Override
    public AccidentSurveyTeamDto findAccidentSurveyTeamById(String id){
        AccidentSurveyTeam accidentSurveyTeam = this.baseMapper.selectById(id);
        AccidentSurveyTeamDto accidentSurveyTeamDto = BeanHelper.copyProperties(accidentSurveyTeam,AccidentSurveyTeamDto.class);
        //小组成员
        AccidentSurveyTeamUser query = new AccidentSurveyTeamUser();
        query.setSurveyTeamId(accidentSurveyTeam.getSurveyTeamId());
        List<AccidentSurveyTeamUser> teamUserList = accidentSurveyTeamUserService.findAccidentSurveyTeamUserList(query);
        accidentSurveyTeamDto.setTeamUserList(teamUserList);
        return accidentSurveyTeamDto;
    }

    /**
     * 新增
     * @author zhangwei
     * @date 2024-09-11 15:21:32
     * @param accidentSurveyTeamDto accidentSurveyTeamDto
     */
    @Override
    @Transactional
    public void createAccidentSurveyTeam(AccidentSurveyTeamDto accidentSurveyTeamDto) {
        AccidentSurveyTeam accidentSurveyTeam = BeanHelper.copyProperties(accidentSurveyTeamDto,AccidentSurveyTeam.class);
        accidentSurveyTeam.setCreatedTime(new Date());
        this.save(accidentSurveyTeam);
        if(!CollectionUtils.isEmpty(accidentSurveyTeamDto.getTeamUserList())){
            accidentSurveyTeamUserService.deleteByTeamIds(accidentSurveyTeamDto.getSurveyTeamId());
            List<AccidentSurveyTeamUser> teamUserList = accidentSurveyTeamDto.getTeamUserList().stream()
                    .map(d -> {
                        AccidentSurveyTeamUser accidentSurveyTeamUser = BeanHelper.copyProperties(d,AccidentSurveyTeamUser.class);
                        accidentSurveyTeamUser.setSurveyTeamId(accidentSurveyTeam.getSurveyTeamId());
                        accidentSurveyTeamUser.setCreatedBy(d.getCreatedBy());
                        accidentSurveyTeamUser.setCreatedTime(new Date());
                        accidentSurveyTeamUser.setTenantId(accidentSurveyTeam.getTenantId());
                        return accidentSurveyTeamUser;
                    }).collect(Collectors.toList());
            accidentSurveyTeamUserService.saveBatch(teamUserList);
        }
    }

    /**
     * 修改
     * @author zhangwei
     * @date 2024-09-11 15:21:32
     * @param accidentSurveyTeamDto accidentSurveyTeamDto
     */
    @Override
    @Transactional
    public void updateAccidentSurveyTeam(AccidentSurveyTeamDto accidentSurveyTeamDto) {
        AccidentSurveyTeam accidentSurveyTeam = BeanHelper.copyProperties(accidentSurveyTeamDto,AccidentSurveyTeam.class);
        accidentSurveyTeam.setUpdatedTime(new Date());
        this.saveOrUpdate(accidentSurveyTeam);
        if(!CollectionUtils.isEmpty(accidentSurveyTeamDto.getTeamUserList())){
            accidentSurveyTeamUserService.deleteByTeamIds(accidentSurveyTeamDto.getSurveyTeamId());
            List<AccidentSurveyTeamUser> teamUserList = accidentSurveyTeamDto.getTeamUserList().stream()
                    .map(d -> {
                        AccidentSurveyTeamUser accidentSurveyTeamUser = BeanHelper.copyProperties(d,AccidentSurveyTeamUser.class);
                        accidentSurveyTeamUser.setSurveyTeamId(accidentSurveyTeam.getSurveyTeamId());
                        accidentSurveyTeamUser.setCreatedBy(d.getCreatedBy());
                        accidentSurveyTeamUser.setCreatedTime(new Date());
                        accidentSurveyTeamUser.setTenantId(accidentSurveyTeam.getTenantId());
                        return accidentSurveyTeamUser;
                    }).collect(Collectors.toList());
            accidentSurveyTeamUserService.saveBatch(teamUserList);
        }
    }

    /**
     * 逻辑删除
     * @author zhangwei
     * @date 2024-09-11 15:21:32
     * @param accidentSurveyTeam accidentSurveyTeam
     * @param accidentSurveyTeamIds accidentSurveyTeamIds
     */
    @Override
    @Transactional
    public void deleteAccidentSurveyTeam(AccidentSurveyTeam accidentSurveyTeam,String accidentSurveyTeamIds) {
        List<String> list = Arrays.asList(accidentSurveyTeamIds.split(StringPool.COMMA));
        this.baseMapper.update(accidentSurveyTeam,new LambdaQueryWrapper<AccidentSurveyTeam>().in(AccidentSurveyTeam::getSurveyTeamId,list));
	}

    /**
    * 物理删除
    * @author zhangwei
    * @date 2024-09-11 15:21:32
    * @param accidentSurveyTeamIds accidentSurveyTeamIds
    */
    @Override
    @Transactional
    public void physicallyDeleteAccidentSurveyTeam(String accidentSurveyTeamIds) {
        List<String> list = Arrays.asList(accidentSurveyTeamIds.split(StringPool.COMMA));
        LambdaQueryWrapper<AccidentSurveyTeam> wapper = new LambdaQueryWrapper<>();
        wapper.in(AccidentSurveyTeam::getSurveyTeamId,list);
        this.remove(wapper);
    }
}
